﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Core.Infrastructure.Controls
{
    [TemplatePart(Name = "EnterAnimation", Type = typeof(Storyboard))]
    [TemplatePart(Name = "LeaveAnimation", Type = typeof(Storyboard))]
    public class ContentControlWithVisualStates : ContentControl
    {
        public Storyboard EnterAnimation
        {
            get { return (Storyboard)GetValue(EnterAnimationProperty); }
            set { SetValue(EnterAnimationProperty, value); }
        }

        public static readonly DependencyProperty EnterAnimationProperty =
            DependencyProperty.Register("EnterAnimation", typeof(Storyboard), typeof(ContentControlWithVisualStates), null);


        public Storyboard LeaveAnimation
        {
            get { return (Storyboard)GetValue(LeaveAnimationProperty); }
            set { SetValue(LeaveAnimationProperty, value); }
        }

        public static readonly DependencyProperty LeaveAnimationProperty =
            DependencyProperty.Register("LeaveAnimation", typeof(Storyboard), typeof(ContentControlWithVisualStates), null);


        public override void OnApplyTemplate()
        {
            var enterAnimation = (Storyboard)base.GetTemplateChild("EnterAnimation");
            var leaveAniamtion = (Storyboard)base.GetTemplateChild("LeaveAnimation");

            if (enterAnimation != null)
            {
                EnterAnimation = enterAnimation;
            }

            if (leaveAniamtion != null)
            {
                LeaveAnimation = leaveAniamtion;
            }

            SubscribeToEvents();
            base.OnApplyTemplate();
        }

        private void SubscribeToEvents()
        {
            RoutedEventHandler handler = null;

            handler = (s, e) =>
            {
                base.Loaded -= handler;
                //VisualStateManager.GoToState(this, "Normal", true);
            };

            base.Loaded += handler;
        }

        protected override void OnContentChanged(object oldContent, object newContent)
        {
            //VisualStateManager.GoToState(this, "NotExisting", true);
            //VisualStateManager.GoToState(this, "Normal", true);
            base.OnContentChanged(oldContent, newContent);
        }
    }
}
